<template>
  <!-- 全屏登录页容器 -->
  <v-sheet class="w-100 h-100 d-flex align-center justify-center login-bg" rounded="lg">
    <v-card class="auth-card" elevation="10" rounded="xl" :width="cardWidth">
      <!-- 头部品牌区 -->
      <v-card-title class="py-6 d-flex align-center justify-center ga-3">
        <v-avatar class="elevation-0" rounded="0" size="40">
          <img alt="logo" :src="logoSrc" style="width: 100%; height: 100%; object-fit: contain" />
        </v-avatar>
        <span class="text-h6 font-weight-bold"
          >{{ mode === 'login' ? '登 录' : '注 册' }} Fieldano</span
        >
      </v-card-title>

      <v-fade-transition mode="out-in">
        <v-card-text v-if="mode === 'login'">
          <!-- 两栏布局：左扫码 / 右密码；底部第三方图标按钮 -->
          <v-row align="center" class="mt-1" justify="center" no-gutters>
            <!-- 左：扫码登录 -->
            <v-col class="d-flex justify-center" cols="12" md="5">
              <div class="d-flex flex-column align-center">
                <v-sheet
                  class="d-flex align-center justify-center"
                  :color="qrLoading ? 'grey-lighten-3' : 'grey-lighten-4'"
                  height="180"
                  rounded="lg"
                  width="180"
                >
                  <v-progress-circular v-if="qrLoading" color="primary" indeterminate />
                  <div v-else class="text-caption d-flex flex-column align-center">
                    <v-icon :icon="mdiQrcodeScan" size="64" />
                    <div class="mt-2">二维码占位（Mock）</div>
                  </div>
                </v-sheet>
                <div class="text-caption text-medium-emphasis mt-2">使用手机App扫描以登录</div>
                <div class="d-flex ga-2 mt-3 mb-4">
                  <v-btn :loading="qrLoading" variant="tonal" @click="refreshQr">刷新二维码</v-btn>
                  <v-btn color="primary" :loading="loading" @click="mockQrSuccess"
                    >模拟扫码成功</v-btn
                  >
                </div>
              </div>
            </v-col>
            <v-divider v-if="$vuetify.display.mdAndUp" vertical></v-divider>
            <!-- 右：账号密码登录 -->
            <v-col class="px-6" cols="12" md="7">
              <v-form ref="formRef" @submit.prevent="onPasswordLogin">
                <v-text-field
                  v-model="account"
                  clearable
                  data-testid="account-user-email"
                  density="comfortable"
                  label="用户名 / 邮箱"
                  :prepend-inner-icon="mdiEmail"
                  rounded="lg"
                  :rules="[]"
                  variant="outlined"
                />
                <v-text-field
                  v-model="password"
                  class="mt-1"
                  data-testid="account-user-password"
                  density="comfortable"
                  :error-messages="errorMsg ? [errorMsg] : []"
                  label="密码"
                  :prepend-inner-icon="mdiLock"
                  rounded="lg"
                  :rules="[]"
                  type="password"
                  variant="outlined"
                />

                <v-btn
                  block
                  class="mt-4"
                  color="primary"
                  data-testid="account-user-button"
                  :loading="loading"
                  size="large"
                  type="submit"
                  >登 录</v-btn
                >
              </v-form>
              <!-- 底部：第三方登录（图标按钮） -->
              <div class="d-flex justify-center ga-4 mt-6">
                <v-btn
                  class="text-white"
                  color="#0A66C2"
                  icon
                  :loading="loading"
                  @click="mockSso('linkedin')"
                >
                  <v-icon :icon="mdiLinkedin" />
                </v-btn>
                <v-btn
                  class="text-white"
                  color="#DB4437"
                  icon
                  :loading="loading"
                  @click="mockSso('google')"
                >
                  <v-icon :icon="mdiGoogle" />
                </v-btn>
                <v-btn
                  class="text-white"
                  color="#1AAD19"
                  icon
                  :loading="loading"
                  @click="mockSso('wechat')"
                >
                  <v-icon :icon="mdiWechat" />
                </v-btn>
              </div>
            </v-col>
          </v-row>

          <!-- 底部辅助信息 -->
          <div class="text-caption text-medium-emphasis mt-6 d-flex justify-space-between">
            <span>这是一个演示用的 Mock 登录，无需真实后端</span>
            <v-btn class="px-1" density="comfortable" variant="text" @click="fillMock"
              >填充示例账号</v-btn
            >
          </div>
          <div class="text-caption mt-2 text-right">
            <v-btn
              class="px-1"
              data-testid="account-user-register"
              density="comfortable"
              variant="text"
              @click="mode = 'register'"
              >没有账号？去注册</v-btn
            >
          </div>
        </v-card-text>
        <RegisterPage v-else @go-login="mode = 'login'" />
      </v-fade-transition>
    </v-card>
  </v-sheet>
</template>

<script lang="ts" setup>
/**
 * 登录页（Mock）
 * - 三种方式：扫码 / 账号密码 / 第三方（LinkedIn、Google、微信）
 * - 登录成功：写入 authState，关闭所有标签页，返回 StartPage
 */
import { computed, ref } from 'vue'
import { useTabStore } from '@/windows/layoutBrowser/stores/tab'
import { type AuthProvider, authState } from '@/windows/layoutBrowser/stores/auth'
import logoSrc from '@/assets/logo-simple.svg'
import { mdiEmail, mdiGoogle, mdiLinkedin, mdiLock, mdiQrcodeScan, mdiWechat } from '@mdi/js'
import RegisterPage from './RegisterPage.vue'

const loading = ref(false)
const qrLoading = ref(false)
const errorMsg = ref('')
const mode = ref<'login' | 'register'>('login')
const cardWidth = computed(() => (mode.value === 'login' ? 700 : 450))

// 表单
const formRef = ref()
const account = ref('')
const password = ref('')
// const rules = {
//   required: (v: string) => (!!v && v.length > 0) || '必填项'
// }

const tabStore = useTabStore()

// 模拟：账号密码登录
async function onPasswordLogin() {
  errorMsg.value = ''
  const valid = await formRef.value?.validate?.()
  if (!valid) return

  loading.value = true
  // 简单 mock：账号为 admin 或邮箱 user@example.com，密码 123456 通过
  const ok =
    (account.value === 'admin' || account.value === 'user@example.com') &&
    password.value === '123456'
  await new Promise(r => setTimeout(r, 600))

  if (!ok) {
    loading.value = false
    errorMsg.value = '账号或密码不正确（演示：admin/123456 或 user@example.com/123456）'
    return
  }

  doLogin('password', { id: 'u_001', name: '演示用户', email: account.value })
}

// 模拟：二维码刷新/成功
function refreshQr() {
  qrLoading.value = true
  errorMsg.value = ''
  setTimeout(() => (qrLoading.value = false), 800)
}

function mockQrSuccess() {
  loading.value = true
  setTimeout(() => doLogin('qrcode', { id: 'u_qr', name: '扫码用户' }), 600)
}

// 模拟：第三方登录
function mockSso(provider: AuthProvider) {
  loading.value = true
  setTimeout(
    () => doLogin(provider, { id: `u_${provider}`, name: provider.toUpperCase() + ' 用户' }),
    700
  )
}

// 统一登录成功处理：写状态 + 回到 StartPage
function doLogin(provider: AuthProvider, user: { id: string; name: string; email?: string }) {
  authState.set({ isLoggedIn: true, user, provider })
  // 关闭所有标签页并回到 StartPage（App.vue 在无活动标签页时会渲染 StartPage）
  try {
    tabStore.closeAllTabs()
    tabStore.setActiveTab(0)
  } catch {}
  loading.value = false
}

function fillMock() {
  account.value = 'admin'
  password.value = '123456'
}
</script>

<style scoped>
.auth-card {
  transition: width 250ms cubic-bezier(0.4, 0, 0.2, 1);
}

.login-bg {
  /* 柔和渐变背景 */
  background:
    radial-gradient(1200px 600px at 10% 10%, rgba(255, 183, 77, 0.15), transparent),
    radial-gradient(900px 500px at 90% 20%, rgba(33, 150, 243, 0.15), transparent),
    linear-gradient(180deg, rgba(0, 0, 0, 0.03), transparent 60%);
}
</style>
